import { useEffect, useState } from "react";
import { Button } from "antd-mobile";

export const SendCodeButton = ({ onSendCode }) => {
  const [countdown, setCountdown] = useState(60);
  const [isCounting, setIsCounting] = useState(false);

  useEffect(() => {
    let intervalId;
    if (isCounting && countdown > 0) {
      intervalId = setInterval(() => {
        setCountdown((prevCount) => prevCount - 1);
      }, 1000);
    } else if (countdown === 0) {
      setIsCounting(false);
      setCountdown(60);
    }
    return () => clearInterval(intervalId);
  }, [countdown, isCounting]);

  const sendCode = () => {
    setIsCounting(true);
    onSendCode();
  };

  return (
    <Button
      size={"small"}
      className={"sms-btn"}
      onClick={isCounting ? null : sendCode}
      disabled={isCounting}
    >
      {isCounting ? `${countdown}s 重发` : "获取验证码"}
    </Button>
  );
};
